package com.yadang.base64;

/**
 * @author: 亚当
 * @date: 2023年02月26日 11:03
 * @package: com.yadang.base64
 * @Description: TODO
 */
import com.yadang.homework.Student;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class CollectionEncryption {
    private static final String AES_ALGORITHM = "AES";
    private static final String ENCRYPT_KEY = "1234567890123456"; // 对称加密秘钥，长度为16位

    // 将List集合加密为字符串
    public static String encryptList(List<?> list) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, ClassNotFoundException {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(list);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byte[] encryptBytes = cipher.doFinal(bytes);
        return Base64.getEncoder().encodeToString(encryptBytes);
    }

    // 将加密的字符串解密为List集合
    public static List<?> decryptList(String encryptedList) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, ClassNotFoundException {
        byte[] encryptBytes = Base64.getDecoder().decode(encryptedList);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] bytes = cipher.doFinal(encryptBytes);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return (List<?>) objectInputStream.readObject();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        // 测试数据，将一个List集合加密并解密
        List<String> list = new ArrayList<>();
        list.add("ASW");
        list.add("WE");
        list.add("你啊哈");
        list.add("jdwiohviwo");
        String encryptedList = encryptList(list);
        System.out.println("加密后：" + encryptedList);
        List<?> decryptedList = decryptList(encryptedList);
        System.out.println("解密后：" + decryptedList);
    }
}
